package com.imooc.miaosha.controller;

import com.imooc.miaosha.domain.MiaoshaUser;
import com.imooc.miaosha.domain.User;
import com.imooc.miaosha.redis.RedisService;
import com.imooc.miaosha.service.GoodsService;
import com.imooc.miaosha.service.MiaoshaUserService;
import com.imooc.miaosha.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("goods")
public class GoodsController {

    @Autowired
    RedisService redisService;

    @Autowired
    MiaoshaUserService miaoshaUserService;

    @Autowired
    GoodsService goodsService;

    @RequestMapping("to_list")
    public String toLogin(Model model, HttpServletResponse response,MiaoshaUser user
        //   @CookieValue(value = MiaoshaUserService.COOKI_NAME_TOKEN,required=false) String cookieToken,
         //                 @RequestParam(value=MiaoshaUserService.COOKI_NAME_TOKEN,required=false) String paramToken
    ){
//        if (StringUtils.isEmpty(cookieToken)&& StringUtils.isEmpty(paramToken)){
//            return "login";
//
//        }
//        String token = StringUtils.isEmpty(paramToken)?cookieToken:paramToken;
//        MiaoshaUser user = miaoshaUserService.getByToken(response,token);
        List<GoodsVo> goods = goodsService.listGoodsVo();
        model.addAttribute("goodsList",goods);
        return "goods_list";
    }

    @RequestMapping("to_detail/{goodsId}")
    public String detail(Model model,MiaoshaUser user,@PathVariable("goodsId") long goodsId
    ){

        model.addAttribute("user", user);
       GoodsVo goodsVo = goodsService.getGoodsVoByGoodsId(goodsId);

       long startAt = goodsVo.getStartDate().getTime();
       long endAt = goodsVo.getEndDate().getTime();
       long now =System.currentTimeMillis();

       int miaoshaStatus = 0;
        int remainSeconds = 0;
       if (now<startAt){// 秒杀还没开始 倒计时
           miaoshaStatus =0;
           remainSeconds = (int)(startAt -now) /1000;
       }else if(now > endAt){ //秒杀已经结束
           miaoshaStatus =2;
           remainSeconds = -1;
       }else{ //秒杀进行中
           miaoshaStatus =1;
           remainSeconds= 0;
       }
        model.addAttribute("miaoshaStatus",miaoshaStatus);
        model.addAttribute("remainSeconds",remainSeconds);
        model.addAttribute("goods",goodsVo);
        return "goods_detail";
    }
}
